<template>
  <div>
    <div class="py-3">
      <el-button type="primary" @click="exportFile">导出</el-button>
      <el-button type="primary" @click="importFile">导入</el-button>
      <!-- 不显示 文件上传的图标 -->
      <input type="file" accept=".xls,.xlsx" ref="inputfile" @change="changeExcel" class="hidden"/>
    </div>
    <el-tree
      :data="treeData"
      ref="treeRef"
      node-key="areaId"
      :props="areaConfig"
      accordion
      lazy
      draggable
      :load="loadNode"
      @node-drop="nodeDrop"
      :allow-drag="(draggingNode) => draggingNode.level !== 1 && draggingNode.level !== 2"
      :allow-drop="(draggingNode, dropNode, type) => dropNode.level >= 3"
      class="w-full"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button v-if="data.areaId !== 0" type="text" size="mini" @click="() => openDialog(data, 0)">添加</el-button>
          <el-button v-if="data.areaId !== 0" type="text" size="mini" @click="() => openDialog(data, 1)">编辑</el-button>
          <el-button v-if="data.areaId !== 0" type="text" size="mini" @click="() => remove(node, data)">删除</el-button>
        </span>
      </span>
    </el-tree>
    <el-dialog
      :visible.sync="dialog.visible"
      :title="dialog.type === 0 ? '新增' : '编辑'"
      width="40%"
    >
      <dmbform
        :model-value="dialog.data"
        :form-items="formBase"
        :colLayout="layout"
        :item-style="itemStyle"
        label-position="top"
        label-width="75px"
        @update="(row) => { dialog.data = Object.assign({}, row) }"
      />
      <div class="flex flex-row-reverse">
        <el-button type="primary" @click="operate">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { deleteRegin, addRegin, editRegin } from '@/api/data/regin-maintenance'
import store from '@/store'
import Dmbform from '@/components/DmbForm/src/index.vue'
import { deepClone } from '@/utils'
import { mapActions } from 'vuex'

const formConfig = {
  areaName: '', // 区域名称
  codeId: '0' // 邮政编码
}

const formBase = [
  {
    label: "区域名称",
    type: "input",
    field: "areaName",
  },
  {
    label: "邮编",
    type: "input",
    otherOptions: {
      type: 'number'
    },
    field: "codeId",
  }
]

const itemStyle = {
  padding: 0,
  marginBottom: '10px'
}

export default {
  name: 'region-maintenance',
  components: { Dmbform },
  data() {
    return {
      areaConfig: {
        label: 'areaName',
        children: 'areaChild'
      },
      treeData: [],
      inputfile: null,
      treeRef: null,
      dialog: {
        visible: false,
        type: 0,
        data: { ...formConfig }
      }, // 弹框对象
      layout: {
        xl: 48, // >1920px 4个
        lg: 48,
        md: 48,
        sm: 48,
        xs: 48,
      }
    }
  },
  computed: {
    // 弹框对象表单格式
    formBase: () => { return formBase },
    // 表单子级样式
    itemStyle: () => { return itemStyle },
    // 原始数据
    area: () => {
      console.log(store.state.custom_dict.area)
      return [{
          areaName: '全部',
          areaId: 0,
          areaChild: store.state.custom_dict.area
      }]
    }
  },
  methods: {
    ...mapActions('custom_dict', ['setDict']),
    // 更新数据且回显
    updateData() {
      this.setDict() // 更新自定义字典
      this.treeData = []
      this.treeData = deepClone(this.area)
    },
    // 打开弹框
    openDialog(data, type) {
      this.dialog.data = Object.assign({}, deepClone(formConfig), data)
      this.dialog.type = type
      this.dialog.visible = true
    },
    // 新增/编辑
    operate() {
      let config = {
        codeId: this.dialog.data.codeId,
        areaName: this.dialog.data.areaName,
        countryId: this.dialog.data.countryId ? this.dialog.data.countryId : this.dialog.data.areaId
      }
      if(this.dialog.type === 0) {
        // 新增
        config.parentId = this.dialog.data.parentId === 0 ? this.dialog.data.areaId : 0
        addRegin(config).then(res => {
          this.$message.success('新增成功')
        })
      } else {
        // 编辑
        config.id = this.dialog.data.areaId
        config.parentId = this.dialog.data.parentId
        editRegin(config).then(res => {
          this.$message.success('编辑成功')
        })
      }
      this.updateData() // 更新
      this.dialog.visible = false
    },
    // 删除单个
    remove(node, data) {
      this.$confirm('此操作将永久删除该地区信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRegin(data.areaId).then(res => {
          this.$message.success('删除成功!')
          this.updateData()
        })
      })
    },
    // 文件导入上传
    changeExcel(e) {
      // 错误情况判断
      const files = e.target.files[0]
      if (files.length <= 0) {
        return false
      }
      let data = new FormData()
      data.append('file', files)
      // 暂无接口
      this.$message.info('暂无接口')
    },
    // 触发导入事件
    importFile() {
      this.$refs.inputfile.click()
    },
    // 导出
    exportFile() {
      this.download('/base/manage/area/export', {
        ...data
      }, `region-maintenance_${new Date().getTime()}.xlsx`)
    },
    // 懒加载指定节点
    loadNode(node, resolve) {
      const data = deepClone(this.area)

      if(node.level === 0) return resolve(data)
      if(node.level === 1) return resolve(data[0].areaChild)
      if(node.level > 1) {
        setTimeout(() => {
          // 如果存在areaChild的时候返回其中的areaChild, 反之则返回空数组防止不停loading
          if(node.data.areaChild) {
            return resolve(node.data.areaChild)
          } else {
            return resolve([]) // 防止不停转圈
          }
        }, 500)
      } else {
        return resolve([]) // 防止不停转圈
      }
    },
    // 拖拽结束事件 // 更改其存在的位置
    nodeDrop(before, after, inner, event) {
      const config = {
        id: before.data.areaId,
        codeId: before.data.codeId,
        areaName: before.data.areaName,
        parentId: after.parent.data.areaId,
        countryId: after.level === 3 ? after.parent.data.areaId : after.parent.data.countryId
      }

      setTimeout(() => {
        editRegin(config).then(res => {
          this.$message.success('修改成功!')
        }).catch(err => {
          this.updateData()
        })
      }, 500)
    }
  }
}
</script>

<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
